//
//  YWTempMissionDBManager.m
//  maintain
//
//  Created by kyo on 16/11/8.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWTempMissionDBManager.h"
#import "YWDBTool.h"
#import "YWCommonTool.h"

#import "YWReply.h"
#import "YWReplyDBManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

@implementation YWTempMissionDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}

NSString* const KSqlCreateTempMissionTable = @"CREATE TABLE IF NOT EXISTS 'tempMission' (tempMissionId integer UNIQUE,title text,content text,fromUserId integer,toUserIds text,createTime timestamp,completionTime timestamp,isRead boolean DEFAULT 0,workSequence text,observerIds varchar);";

#pragma mark - 临时任务
- (BOOL)createTempMissionTable
{
    NSString* sql = KSqlCreateTempMissionTable;
    return [[self fmdb] executeUpdate:sql];
}

- (void)dropAndReCreateTempMissionTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists tempMission;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateTempMissionTable];
        }
    }];
}

- (BOOL)updateTempMissionWithTempMissionArray:(NSArray*)tempMissions
{
    if (tempMissions.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockTempMissions = tempMissions;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        
        [blockTempMissions enumerateObjectsUsingBlock:^(YWTempMission* _Nonnull tempMission, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'tempMission' WHERE tempMissionId=? ;";
            FMResultSet* set = [db executeQuery:sql, @(tempMission.tempMissionId)];
            if ([set next]) {
                sql = @"UPDATE 'tempMission' SET title=? ,content=? ,fromUserId =?,toUserIds=?, createTime=?,completionTime=?,workSequence=?,observerIds=? WHERE tempMissionId=?;";
                executeResult = [db executeUpdate:sql, tempMission.title, tempMission.content, @(tempMission.fromUser.uniqueId), tempMission.toUserIds, @(tempMission.createTime), @(tempMission.completionTime),tempMission.workSequence,tempMission.observerIds, @(tempMission.tempMissionId)];
            }
            else {
                sql = @"INSERT INTO 'tempMission' (tempMissionId,title,content,fromUserId,toUserIds,createTime,completionTime,workSequence,observerIds) VALUES (?, ?, ?, ?, ?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, @(tempMission.tempMissionId), tempMission.title, tempMission.content, @(tempMission.fromUser.uniqueId), tempMission.toUserIds, @(tempMission.createTime), @(tempMission.completionTime),tempMission.workSequence,tempMission.observerIds];
            }
            //这里是防止别人修改临时任务图片，把图片删除光了，在更新图片的时候没有删除
            if (tempMission.imagesList.count==0) {
                NSString* sql = @"delete FROM 'record_picture' WHERE recordId=?";
                executeResult = [db executeUpdate:sql, @(tempMission.tempMissionId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
//    __block NSMutableArray* recordsArray = [NSMutableArray array];
    __block NSMutableArray* picturesArray = [NSMutableArray array];
    __block NSMutableArray* attachmentsArray = [NSMutableArray array];
    [blockTempMissions enumerateObjectsUsingBlock:^(YWTempMission* _Nonnull tempMission, NSUInteger idx, BOOL* _Nonnull stop) {
        //图片
        [tempMission.imagesList enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull patrolPicture, NSUInteger idx, BOOL* _Nonnull stop) {
            patrolPicture.recordId = [NSString stringWithFormat:@"%ld", (long)tempMission.tempMissionId];
            patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
            patrolPicture.recordType = YWPictureRecordTypeTempMission;
        }];
        [picturesArray addObjectsFromArray:tempMission.imagesList];
        
        //附件
        [tempMission.attachmentList enumerateObjectsUsingBlock:^(YWattachment* _Nonnull attachment, NSUInteger idx, BOOL* _Nonnull stop) {
            attachment.recordId = tempMission.tempMissionId;
            attachment.attachmentType = YWattachmentTypeOfTempMission;
        }];
        [attachmentsArray addObjectsFromArray:tempMission.attachmentList];
        
        //评论
//        [tempMission.workReplyList enumerateObjectsUsingBlock:^(YWReply*  _Nonnull reply, NSUInteger idx, BOOL * _Nonnull stop) {
//            reply.relationId = tempMission.tempMissionId;
//            reply.relationType = YWReplyRelationTypeTempMission;
//        }];
//        [recordsArray addObjectsFromArray:tempMission.workReplyList];
        
        //保存执行人
        [[YWDBTool shareDBTool] updateHandlerWithArray:tempMission.executors];
        //保存发布人
        if (tempMission.fromUser) {
            [[YWDBTool shareDBTool] updateHandlerWithArray:@[ tempMission.fromUser ]];
        }
    }];
//    [[YWReplyDBManager shareManager] updateReplyWithReplyArray:recordsArray];
    [[YWDBTool shareDBTool] updatePatrolPictureWithNewWorkData:picturesArray];
    [[YWDBTool shareDBTool] updateAttachmentWithAttachments:attachmentsArray];
    return executeResult;
}
- (NSArray*)tempMissionOfTypeWithMeOrOthers:(YWTempMissionType)tempMissionType page:(NSInteger)page
{
    __block NSMutableArray* blockTempMissions = [NSMutableArray array];
    __block NSMutableArray *allTempMissions = [NSMutableArray array];
    __block YWLoginUser* currentUser = [YWLoginTool loginUser];
    __block NSString* sql = @"";
    __block NSInteger showCount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        FMResultSet* set = nil;
        if (tempMissionType == YWTempMissionTypeOfMe) {
            sql = @"SELECT * FROM 'tempMission' where fromUserId=? ORDER BY createTime desc  LIMIT ?";
            set = [db executeQuery:sql, @(currentUser.uniqueId), @(showCount)];
        }
        else if (tempMissionType == YWTempMissionTypeOfOthers) {
            sql = @"SELECT * FROM 'tempMission' where fromUserId!=? ORDER BY createTime desc  LIMIT ?";
            set = [db executeQuery:sql, @(currentUser.uniqueId), @(showCount)];
        }
        else {
            sql = @"SELECT * FROM 'tempMission' ORDER BY createTime desc  LIMIT ?";
            set = [db executeQuery:sql, @(showCount)];
        }
        
        //按照时间排序后，构建二维数组，UI按照时间段显示
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWTempMission* tempMission = [self tempMissionWithFMResultSet:set FMDatabase:db];
            [allTempMissions addObject:tempMission];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:tempMission.createTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:tempMission];
            if (![blockTempMissions containsObject:array] && array.count) {
                [blockTempMissions addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return blockTempMissions.count ? blockTempMissions : nil;
}

- (YWTempMission*)tempMissionWithTempMissionId:(NSInteger)tempMissionId
{
    __block YWTempMission* tempMission = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'tempMission' where tempMissionId=? ";
        FMResultSet* set = [db executeQuery:sql, @(tempMissionId)];
        while ([set next]) {
            tempMission = [self tempMissionWithFMResultSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    if (tempMission) {
        NSMutableArray* handlers = [NSMutableArray array];
        NSArray* list = [tempMission.toUserIds componentsSeparatedByString:@","];
        for (int i = 0; i < list.count; i++) {
            NSInteger userId = [list[i] integerValue];
            YWHandler* handler = [[YWDBTool shareDBTool] handlerWithUniqueId:userId];
            if (handler) {
                [handlers addObject:handler];
            }
        }
        tempMission.executors = handlers;
    }
    return tempMission;
}

- (BOOL)existTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    __block BOOL ret = NO;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* selectSQL = @"SELECT * FROM 'tempMission' WHERE tempMissionId=?;";
        FMResultSet* set = [db executeQuery:selectSQL,@(tempMissionId)];
        if ([set next]) {
            ret = YES;
        }
        [db closeOpenResultSets];
    }];
    return ret;
}

- (BOOL)deleteTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"DELETE FROM 'tempMission' where tempMissionId=? ";
        executeResult = [db executeUpdate:sql, @(tempMissionId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}


- (BOOL)deletePictureOfTempMissionWithTempMissionId:(NSInteger)tempMissionId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"delete FROM 'record_picture' WHERE recordId=?";
        executeResult = [db executeUpdate:sql, @(tempMissionId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWTempMission*)tempMissionWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWTempMission* tempMission = [[YWTempMission alloc] init];
    tempMission.tempMissionId = [set intForColumn:@"tempMissionId"];
    tempMission.title = [set stringForColumn:@"title"];
    tempMission.content = [set stringForColumn:@"content"];
    tempMission.createTime = [set longLongIntForColumn:@"createTime"];
    tempMission.completionTime = [set longLongIntForColumn:@"completionTime"];
    tempMission.isRead = [set boolForColumn:@"isRead"];
    tempMission.workSequence = [set stringForColumn:@"workSequence"];
    tempMission.observerIds = [set stringForColumn:@"observerIds"];
    tempMission.toUserIds = [set stringForColumn:@"toUserIds"];
    NSMutableArray *executorArray = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM 'handler' WHERE uniqueId in (%@)",tempMission.toUserIds];
    FMResultSet *newSet = [db executeQuery:sql];
    while ([newSet next]) {
        YWHandler *handler = [[YWDBTool shareDBTool] handlerWithSet:newSet];
        [executorArray addObject:handler];
    }
    tempMission.executors = executorArray;
    
    
    NSInteger creatorId = [set intForColumn:@"fromUserId"];
    sql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    newSet = [db executeQuery:sql, @(creatorId)];
    if ([newSet next]) {
        tempMission.fromUser = [[YWDBTool shareDBTool] handlerWithSet:newSet];
    }
    
    NSMutableArray *observer = [NSMutableArray array];
    sql = [NSString stringWithFormat:@"SELECT * FROM 'handler' WHERE uniqueId in (%@)",tempMission.observerIds];
    newSet = [db executeQuery:sql];
    while ([newSet next]) {
        YWHandler *handler = [[YWDBTool shareDBTool] handlerWithSet:newSet];
        [observer addObject:handler];
    }
    tempMission.observers = observer;
    return tempMission;
}
- (BOOL)setTempMissionIsRead:(YWTempMission*)tempMission
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'tempMission' SET isRead=? WHERE tempMissionId=?;";
        executeResult = [db executeUpdate:sql, @(1), @(tempMission.tempMissionId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (BOOL)setAllTempMissionIsRead
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'tempMission' SET isRead=1;";
        executeResult = [db executeUpdate:sql];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (NSInteger)tempMissionNoReadCount
{
    __block NSInteger noReadCount = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* countSql = @"SELECT COUNT(*) AS noReadCount FROM 'tempMission' WHERE isRead=0";
        FMResultSet* countSet = [db executeQuery:countSql];
        if ([countSet next]) {
            noReadCount = [countSet intForColumn:@"noReadCount"];
        }
        [db closeOpenResultSets];
    }];
    return noReadCount;
}
@end
